// json对象转换成字符串
export const jsonToStr = json => JSON.stringify(json, function(key, val) {
  if (typeof val === "function") {
    return val + "";
  }
  return val;
});
// json字符串转换成对象
export const strToJson = s => JSON.parse(s, function(k, v) {
  if (v.indexOf && v.indexOf("function") > -1) {
    return eval("(function(){return " + v + " })()");
  }
  return v;
});

export const setValue = (keys,value,datas) =>{
  let [key, ...child] = keys
    if (keys.length == 1) {
      datas[key] = value
    } else {
      if (!datas.hasOwnProperty(key)){
        datas[key]={}
      }
      let {
        [key]: data
      } = datas
      console.log(datas)
      setValue(child, value, data)
    }
}

export const saveJson = (json,filename)=>{
  if (!json){
    console.error("缺失json数据!")
    return;
  }
  if (!filename){
    filename = "json.json"
  }
  if (typeof json === 'object') {
    json = jsonToStr(json)
  }
  var blob = new Blob([json], { type: 'text/json' });
  var e = document.createEvent('MouseEvents');
  var a = document.createElement('a');
  a.download = filename;
  a.href = window.URL.createObjectURL(blob);
  a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
  e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  a.dispatchEvent(e);
}

export const saveText = (text,filename) => {
  if (!text){
    console.error("缺失json数据!")
    return;
  }
  if (!filename){
    filename = "text.txt"
  }
  if (typeof text != 'string') {
    text = text+""
  }
  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename);
 
  element.style.display = 'none';
  document.body.appendChild(element);
  element.click();
}